package com.bestcem.xm.ticket.grpc.client;

import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.xm.award.grpc.v1.services.Award;
import com.bestcem.xm.award.grpc.v1.services.AwardServiceGrpc;
import com.bestcem.xm.award.grpc.v1.services.GetAwardRequest;
import com.bestcem.xm.award.grpc.v1.services.GetAwardResponse;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.ticket.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.Optional;

/**
 * 奖励模块 手动编写的client 方法
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/2 16:30
 */
@Slf4j
@Service
public class TicketAwardGrpcService {

    @GrpcClient(GrpcClientNames.DS_AWARD)
    private AwardServiceGrpc.AwardServiceBlockingStub awardServiceBlockingStub;

    /**
     * 根据id获取奖励名字
     *
     * @param id 奖励id
     * @return 奖励名字
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/9/2 16:49
     */
    @Nonnull
    public String getAwardName(String id) {
        GetAwardRequest.Builder builder = GetAwardRequest.newBuilder();
        builder.setId(id);
        try {
            GetAwardResponse response = awardServiceBlockingStub.getAward(builder.buildPartial());
            if (Objects.isNull(response) || Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] AWARD getAwardName {} Error; ErrorMsg: {}", id, response);
                return Constants.BLANK;
            }
            Award award = response.getAward();
            return Optional.of(award).map(Award::getName).orElse(Constants.BLANK);
        } catch (Exception e) {
            log.error("[Ticket] AWARD getAwardName {} Error;", id, e);
            return Constants.BLANK;
        }
    }
}
